<template>
    <div>
        <el-button type="primary" @click="save2pic">保存图片</el-button>
        <div ref="menuTree" class="ivrtree">
            <vue2-org-tree
                :data="dataTree"
                :horizontal="horizontal"
                :collapsable="collapsable"
                :label-class-name="labelClassName"
                @on-node-click="onNodeClick"
            ></vue2-org-tree>

            <!-- 弹出框 -->
            <el-dialog
                v-drag
                title="编辑"
                :visible.sync="editVisible"
                width="600px"
                :append-to-body="true"
                @closed="dialogClosed"
                class="ivrtreeDialog"
            >
                <el-form
                    ref="form-edit"
                    label-width="70px"
                    v-model="treeNode"
                    :label-position="labelPosition"
                >
                    <el-form-item label="ID" v-show="false">
                        <el-input disabled v-model="treeNode.id" />
                    </el-form-item>
                    <el-form-item label="节点名称">
                        <el-input disabled v-model="treeNode.label" />
                    </el-form-item>
                    <el-form-item label="语音名称" v-if="isMenuVisible">
                        <el-input disabled v-model="treeNode.wavName" />
                    </el-form-item>
                    <el-form-item label="语音内容">
                        <el-input
                            type="textarea"
                            v-model="treeNode.nodeName"
                            :placeholder="placeholder"
                            maxlength="200"
                            show-word-limit
                            rows="4"
                        />
                    </el-form-item>
                    <el-form-item label="有效日期" v-if="isSloganVisible">
                        <div>
                            <el-col :span="11">
                                <el-date-picker
                                    type="date"
                                    placeholder="开始日期"
                                    style="width: 100%;"
                                    v-model="startDate"
                                    format="yyyy年MM月dd日"
                                ></el-date-picker>
                            </el-col>
                            <el-col class="line" :span="2" style="padding-left: 5px">至</el-col>
                            <el-col :span="11">
                                <el-date-picker
                                    type="date"
                                    placeholder="结束日期"
                                    style="width: 100%;"
                                    v-model="endDate"
                                    format="yyyy年MM月dd日"
                                ></el-date-picker>
                            </el-col>
                        </div>
                        <div class="el-upload__tip">
                            <span>若日期均为空，长期有效;&nbsp;&nbsp;</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="文件上传" v-else>
                        <el-upload
                            class="upload-demo"
                            :action="uploadPath"
                            :show-file-list="true"
                            ref="upload"
                            accept="wav"
                            :before-upload="beforeUpload"
                            :on-success="uploadSuccess"
                            :on-error="uploadError"
                            :file-list="fileList"
                        >
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">点击上传</div>
                            <div
                                class="el-upload__tip"
                                slot="tip"
                            >后缀：.wav &nbsp;&nbsp;&nbsp; 属性：A-Law，8000Hz，64kbps</div>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button
                        size="small"
                        icon="el-icon-circle-close"
                        @click="editVisible = false"
                    >取 消</el-button>
                    <el-button type="primary" @click="save">保 存</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { TreeApi } from "./TreeApi";
import html2canvas from 'html2canvas';

export default {
    name: 'IVRtree',
    data() {
        return {
            uploadPath: "",
            labelPosition: "left",
            editVisible: false,
            isSloganVisible: false,
            isMenuVisible: false,
            dataTree: {},
            horizontal: true,
            collapsable: false,
            expandAll: true,
            labelClassName: "bg-green",
            fileList: [],
            treeNode: {},
            startDate: null,
            endDate: null,
            placeholder: null
        }
    },
    async created() {
        await this.getParams();
        this.uploadPath = TreeApi.RequestUrl + "/uploadFile";

        this.reload();
    },
    methods: {
        /**
         * 日期格式化
         * date
         * format[yyyyMMdd, yyyy年MM月dd日]
         * 默认：yyyy年MM月dd日
         */
        dateFormat(date, format) {
            let year = date.getFullYear();
            let m = date.getMonth() + 1;
            let month = (m < 10) ? '0' + m : m;
            let d = date.getDate();
            let day = (d < 10) ? '0' + d : d;
            if (format !== undefined && format === 'yyyyMMdd') {
                return year + '' + month + '' + day;
            } else {
                return year + "年" + month + "月" + day + "日";
            }
        },
        dateStr2Date(dateStr) {
            let y = dateStr.substring(0, 4);
            let m = dateStr.substring(4, 6);
            let d = dateStr.substring(6, 8);
            return y + "/" + m + "/" + d;
        },
        /**
         * dialog关闭后回调
         */
        dialogClosed() {
            this.fileList = [];
            this.treeNode = {};
            this.startDate = null;
            this.endDate = null;
        },
        reload() {
            console.log('TreeApi', TreeApi);
            TreeApi.getAllTree().then(resp => {
                if (resp.code === 'OK') {
                    this.dataTree = resp.data;
                } else {
                    this.dataTree = {
                        "id": 0,
                        "label": "获取菜单树失败",
                        "nodeType": "ERROR"
                    };
                }
            });
        },
        onNodeClick(e, data) {
            if (data.nodeType !== "ERROR") {
                this.editVisible = true;
                this.isSloganVisible = (data.nodeType === 'SLOGAN') ? true : false;
                this.isMenuVisible = (data.nodeType === 'MENUE') ? true : false;

                this.treeNode = JSON.parse(JSON.stringify(data));
                //删除copy节点children属性
                delete this.treeNode.children;

                if (this.treeNode.nodeType === 'SLOGAN') {
                    this.placeholder = "设置语音内容，200字以内";
                    let wavName = this.treeNode.wavName;
                    if (wavName !== '' && wavName !== null) {
                        let dateStr = wavName.split('-');
                        this.startDate = new Date(Date.parse(this.dateStr2Date(dateStr[0])));
                        this.endDate = new Date(Date.parse(this.dateStr2Date(dateStr[1])));
                    }
                } else {
                    this.placeholder = "备注更新语音内容，200字以内";
                }
            }
        },
        getCurrentDateStr() {
            let currentDate = new Date();
            let dateStr = this.dateFormat(currentDate, "yyyyMMdd");
            let h = currentDate.getHours();
            let hours = (h < 10) ? '0' + h : h;
            let m = currentDate.getMinutes();
            let mi = (m < 10) ? '0' + m : m;
            let s = currentDate.getSeconds();
            let sc = (s < 10) ? '0' + s : s;
            return dateStr + hours + mi + sc;
        },
        fileDownLoad(downLoadUrl) {
            let pngName = this.getCurrentDateStr() + ".png";
            let aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = downLoadUrl;
            aLink.download = pngName;
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
        },
        save2pic() {
            html2canvas(this.$refs.menuTree, { width: 1600, height: 1300 }).then((canvas) => {
                let dataURL = canvas.toDataURL("image/png");
                this.fileDownLoad(dataURL);
            });
        },
        /**
         * 自定义节点样式
         * @param h
         * @param data
         * @returns {boolean}
         */
        // renderContent(h, data) {
        //     return (
        //         < span style="width:100%;height:100%;display:block;border-radius:3px;" >
        //             {data.label}
        //             < /span>
        //     );
        // },
        beforeUpload(file) {
            let idx = file.name.indexOf(".");
            let fileName = file.name.substr(0, idx);
            let fileFormat = file.name.substr(idx + 1);

            if (fileFormat !== "wav") {//wav音频
                this.$message.error("请选择wav音频文件");
                return false;
            }

            let name = this.treeNode.wavName;
            if (fileName !== name) {
                this.$message.error("上传文件名称与语音名称不一致，请修改");
                return false;
            }
        },
        uploadError(err, file) {
            this.$message.error("上传失败");
        },
        uploadSuccess(response, file,) {
            this.$message.success("上传成功");
        },
        save() {
            if (this.treeNode.nodeType === 'SLOGAN') {
                if (this.startDate !== null && this.endDate === null) {
                    this.$message.error("请选择结束日期");
                    return;
                }

                if (this.endDate !== null && this.startDate === null) {
                    this.$message.error("请选择开始日期");
                    return;
                }

                if (this.startDate !== null && this.endDate !== null) {
                    let start = new Date(this.startDate);
                    let end = new Date(this.endDate);
                    if (start.getTime() > end.getTime()) {
                        this.$message.error("开始日期不能大于结束日期");
                        return;
                    }

                    let startStr = this.dateFormat(start, 'yyyyMMdd');
                    let endStr = this.dateFormat(end, 'yyyyMMdd');
                    this.treeNode.wavName = startStr + "-" + endStr;
                } else {
                    this.treeNode.wavName = '';
                }
            }
            TreeApi.updateTreeNode(this.treeNode).then(resp => {
                if (resp.code === 'OK') {
                    this.$message.success("保存成功");
                    this.editVisible = false;
                    this.reload();
                } else {
                    this.$message.error("保存失败");
                }
            });
        },
        // 获取 IVR语音菜单Ip 对应的服务地址参数
        async getParams() {
            await this.$post.Params.searchListByParam({ paramType: 'IVR语音菜单' }).then((res) => {
                if (res.data.success) {
                    const arr = JSON.parse(JSON.stringify(res.data.content));
                    arr.forEach((item) => {
                        if (item.paramCode === 'ivr_server_ip') {
                            // this.paramsObj[item.paramCode] = item.paramValue;
                            TreeApi.RequestUrl = item.paramValue;
                        }
                    });
                } else {
                    TreeApi.RequestUrl = TreeApi.RequestUrl;
                    this.$message.error(res.data.msg);
                }
            });
        },
    }
};
</script>
<style lang="scss" >
.ivrtreeDialog {
    /* 上传图标调整 */
    .upload-demo {
        .el-upload {
            width: 200px;
            height: 100px;
            border: 1px solid #ccc;
            border-radius: 4px;
            color: #409eff;
        }
        .el-icon-upload {
            margin-top: 10px;
            font-size: 36px;
        }
    }
}
.ivrtree {
    background-color: #fff;
    text-align: left;
    .el-upload--text {
        width: 100%;
        height: auto;
    }
    .el-upload__tip {
        margin-top: 0px;
    }
    .org-boxs {
        width: 100%;
        height: 100%;
        /* text-align: center; */
        /*background: #030C24;*/
        background-image: -webkit-radial-gradient(
            ellipse farthest-corner at center 40%,
            #000d4d 0%,
            #000105 100%
        );
        background-image: radial-gradient(
            ellipse farthest-corner at center 40%,
            #000d4d 0%,
            #000105 100%
        );
        overflow-y: scroll;
    }
    .org-tree-container {
        display: inline-block;
        padding: 20px 10px;
        text-align: left;
        margin-left: 35px;
        /*background-color: #fff;*/
        > .org-tree > .org-tree-node {
            padding-bottom: 20px;
        }
    }
    .bg-green {
        background-color: #409eff; // #c3ffcd;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
    }
    .org-tree {
        // display: inline-block;
        display: table;
        /* text-align: center; */

        &:before,
        &:after {
            content: "";
            display: table;
        }

        &:after {
            clear: both;
        }
    }

    .org-tree-node,
    .org-tree-node-children {
        position: relative;
        margin: 0;
        padding: 0;
        list-style-type: none;

        &:before,
        &:after {
            transition: all 0.35s;
        }
    }
    .org-tree-node-label {
        position: relative;
        display: inline-block;

        .org-tree-node-label-inner {
            padding: 5px 10px;
            text-align: center;
            border-radius: 3px;
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15);
        }
    }
    .org-tree-node-btn {
        position: absolute;
        top: 100%;
        left: 50%;
        width: 20px;
        height: 20px;
        z-index: 10;
        margin-left: -11px;
        margin-top: 9px;
        background-color: #fff;
        border: 1px solid #1faaeb;
        border-radius: 50%;
        box-shadow: 0 0 2px rgba(0, 0, 0, 0.15);
        cursor: pointer;
        transition: all 0.35s ease;

        &:hover {
            background-color: #e7e8e9;
            transform: scale(1.15);
        }

        &:before,
        &:after {
            content: "";
            position: absolute;
        }

        &:before {
            top: 50%;
            left: 4px;
            right: 4px;
            height: 0;
            border-top: 1px solid #1faaeb;
        }

        &:after {
            top: 4px;
            left: 50%;
            bottom: 4px;
            width: 0;
            border-left: 1px solid #1faaeb;
        }

        &.expanded:after {
            border: none;
        }
    }
    .org-tree-node {
        padding-top: 20px;
        display: table-cell;
        vertical-align: top;

        &.is-leaf,
        &.collapsed {
            padding-left: 2px;
            padding-right: 5px;
        }

        &:before,
        &:after {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 50%;
            height: 19px;
        }

        &:after {
            left: 50%;
            border-left: 1px solid #1faaeb;
        }

        &:not(:first-child):before,
        &:not(:last-child):after {
            border-top: 1px solid #1faaeb;
        }
    }
    .collapsable .org-tree-node.collapsed {
        padding-bottom: 30px;
        .org-tree-node-label:after {
            content: "";
            position: absolute;
            top: 100%;
            left: 0;
            width: 50%;
            height: 20px;
            border-right: 1px solid #1faaeb;
        }
    }
    .org-tree > .org-tree-node {
        padding-top: 0;

        &:after {
            border-left: 0;
        }
    }
    .org-tree-node-children {
        padding-top: 20px;
        display: table;

        &:before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 50%;
            height: 20px;
            border-right: 1px solid #1faaeb;
            border-left: none;
        }

        &:after {
            content: "";
            display: table;
            clear: both;
        }
    }

    .horizontal {
        .org-tree-node {
            // display: flex;
            // flex-direction: row;
            // justify-content: flex-start;
            // align-items: center;
            display: table-cell;
            float: none;
            padding-top: 0;
            padding-left: 20px;

            &.is-leaf,
            &.collapsed {
                padding-top: 2px;
                padding-bottom: 5px;
            }

            &:before,
            &:after {
                width: 19px;
                height: 50%;
            }

            &:after {
                top: 50%;
                left: 0;
                border-left: 0;
            }

            &:only-child:before {
                top: 1px;
                border-bottom: 1px solid #1faaeb;
            }

            &:not(:first-child):before,
            &:not(:last-child):after {
                border-top: 0;
                border-left: 1px solid #1faaeb;
            }

            &:not(:only-child):after {
                border-top: 1px solid #1faaeb;
            }

            .org-tree-node-inner {
                display: table;
            }
        }

        .org-tree-node-label {
            display: table-cell;
            vertical-align: middle;
        }

        &.collapsable .org-tree-node.collapsed {
            padding-right: 30px;

            .org-tree-node-label:after {
                top: 0;
                left: 100%;
                width: 20px;
                height: 50%;
                border-right: 0;
                border-bottom: 1px solid #1faaeb;
            }
        }

        .org-tree-node-btn {
            top: 50%;
            left: 100%;
            margin-top: -11px;
            margin-left: 9px;
        }

        & > .org-tree-node:only-child:before {
            border-bottom: 0;
        }

        .org-tree-node-children {
            // display: flex;
            // flex-direction: column;
            // justify-content: center;
            // align-items: flex-start;
            display: table-cell;
            padding-top: 0;
            padding-left: 20px;

            &:before {
                top: 50%;
                left: 0;
                width: 20px;
                height: 0;
                border-left: 0;
                border-top: 1px solid #1faaeb;
            }

            &:after {
                display: none;
            }

            & > .org-tree-node {
                display: block;
            }
        }
    }
}
</style>